package com.jsbb.service.tool;

import com.jsbb.dto.tool.TableQueryDto;
import com.jsbb.util.DateUtils;
import com.jsbb.util.SqlUtils;
import com.jsbb.vo.tool.ColumnListVo;
import com.jsbb.vo.tool.TableListVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据库表Service
 *
 * @author w
 * @date 2021-03-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TableService {

    public List<TableListVo> list(TableQueryDto queryDto) {
        List<TableListVo> result = new ArrayList<>();
        List<Map<String, String>> list = SqlUtils.selectTableInfo(queryDto.getIp(), queryDto.getPort(), queryDto.getSchema(), queryDto.getUser(), queryDto.getPassword());
        Map<String, List<Map<String, String>>> map = list.stream().collect(Collectors.groupingBy(e -> e.get("tableName"), TreeMap::new, Collectors.toList()));
        Iterator tableIt = map.entrySet().iterator();
        while (tableIt.hasNext()) {
            Map.Entry entry = (Map.Entry) tableIt.next();
            List<Map<String, String>> columnList = (List<Map<String, String>>) entry.getValue();
            TableListVo table = new TableListVo();
            table.setTableName(columnList.get(0).get("tableName"));
            table.setTableComment(columnList.get(0).get("tableComment"));
            table.setColumnSize(columnList.size());
            table.setCreateTime(DateUtils.parseDate(columnList.get(0).get("createTime"), DateUtils.YMD_DATA));
            List<ColumnListVo> fieldList = new ArrayList<>();
            for (Map<String, String> column : columnList) {
                ColumnListVo field = new ColumnListVo();
                field.setColumnName(column.get("columnName"));
                field.setColumnComment(column.get("columnComment"));
                field.setColumnType(column.get("columnType"));
                field.setIsNullable("NO".equals(column.get("isNullable")) ? "否" : "是");
                field.setColumnKey(StringUtils.hasText(column.get("columnKey")) ? "是" : "");
                fieldList.add(field);
            }
            table.setColumnList(fieldList);
            result.add(table);
        }
        return result;
    }
}
